<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card style="margin-top:20px;">
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="+activeIndex" align-center style="margin:20px 0;">
        <el-step title="基本信息"></el-step>
        <el-step title="命名参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabs"
          @tab-click="tabsClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称：" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格：" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量：" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量：" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类：">
              <el-cascader
                v-model="addForm.goods_cat"
                :props="{label: 'cat_name',value: 'cat_id',children: 'children'}"
                :options="cateList"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="命名参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(val,index) in item.attr_vals" :key="index" :label="val"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="uploadSuccess"
              :before-remove="beforeImgRemove"
              :before-upload="beforeImgUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <div id="editor" class="editor"></div>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片浏览文本框 -->
    <el-dialog title="图片浏览" :visible.sync="imgVisible" width="50%">
      <img style="width:100%" :src="fileimg" alt />
    </el-dialog>
  </div>
</template>
<script>
import E from "wangeditor";
// 导入wangeditor
export default {
  created() {
    this.getCateList();
  },
  mounted() {
    var editor = new E("#editor");
    editor.customConfig.onchange = html => {
      this.addForm.goods_introduce = html;
    };
    editor.create();
  },
  data() {
    return {
      imgVisible: false,
      fileimg: "",
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_cat: [],
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        goods_introduce: "",
        pics: [],
        attrs: []
      },
      //   表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ]
      },
      //   cateList 类别数据
      cateList: [],
      //   many动态参数数据列表
      manyList: [],
      //   only动态参数数据列表
      onlyList: [],
      //   上传图片请求头信息
      headersObj: {
        Authorization: sessionStorage.getItem("token")
      }
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateList = res.data;
    },
    //   获取动态many数据
    async getmanyList() {
      let id = this.addForm.goods_cat[2];
      // 发送请求 根据activeName获取数据
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes`,
        { params: { sel: "many" } }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(" ")
          : [];
      });
      this.manyList = res.data;
      console.log(this.manyList);
    },
    // 获取静态only数据
    async getonlyList() {
      let id = this.addForm.goods_cat[2];
      // 发送请求 根据activeName获取数据
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes`,
        { params: { sel: "only" } }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.onlyList = res.data;
    },
    //   级联选择器触发事件
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return;
      }
    },
    // 标签切换时要执行的方法
    beforeTabs(newtabs, oldtabs) {
      if (newtabs === "1" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请填写必要数据");
        return false;
      } else if (newtabs === "2" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请填写必要数据");
        return false;
      } else if (newtabs === "3" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请填写必要数据");
        return false;
      } else if (newtabs === "4" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请填写必要数据");
        return false;
      }
    },
    // 标签切换发送数据获取请求
    tabsClick() {
      if (this.activeIndex === "1") {
        this.getmanyList();
      } else if (this.activeIndex === "2") {
        this.getonlyList();
      }
    },
    // 图片上传之前调用的函数
    beforeImgUpload(file) {
      let ispng = file.type === "image/png";
      let isjpg = file.type === "image/jpeg";
      let issize = file.size / 1024 <= 1024;
      if (!ispng && !isjpg) {
        this.$message({
          message: "请上传对应文件",
          type: "warning",
          offset: 10
        });
      }
      if (!issize) {
        this.$message({
          message: "请上传不超于1MB大小图片",
          type: "error",
          offset: 50
        });
      }
      return (ispng || isjpg) && issize;
    },
    // 图片上传成功时调用的函数
    uploadSuccess(response) {
      let pic = { pic: response.data.tmp_path };
      this.addForm.pics.push(pic);
    },
    // 点击图片文字调用的函数
    handlePreview(file) {
      this.imgVisible = true;
      this.fileimg = file.response.data.url;
    },
    // 删除之前调用的函数
    beforeImgRemove(file) {
      if (file.status !== "success") return;
      return this.$confirm(`此操作将永久删除${file.name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => {
        this.$message.info("取消了删除");
        reject();
      });
    },
    // 删除时调用
    handleRemove(file) {
      if (file.status !== "success") return;
      let pathindex = this.addForm.pics.findIndex(item => {
        item.pic === file.response.data.tmp_path;
      });
      this.addForm.pics.splice(pathindex, 1);
    },
    // 点击添加按钮执行添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        var deep = _.cloneDeep(this.addForm);
        this.manyList.forEach(item => {
          const newInfo = {
            attr_id: item.id,
            attr_vals: item.attr_vals.join(" ")
          };
          this.addForm.attrs.push(newInfo);
        });
        this.onlyList.forEach(item => {
          const newInfo = {
            attr_id: item.id,
            attr_vals: item.attr_vals
          };
          this.addForm.attrs.push(newInfo);
        });
        deep.goods_cat = deep.goods_cat.join(",");
        deep.attrs = this.addForm.attrs;
        const { data: res } = await this.$http.post("goods", deep);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.$router.push("/goods");
      });
    }
  }
};
</script>
<style lang="less" scoped>
</style>